<?php
/*
 * @Author: Terry
 * @Date: 2025-03-20 17:46:08
 * @LastEditors: Terry
 * @LastEditTime: 2025-03-28 17:27:40
 * @Description: file content
 * @FilePath: \yyd_api\app\controller\user\v1\Auth.php
 */
declare (strict_types = 1);

namespace app\controller\user\v1;

use app\BaseController;
use think\facade\Db;
use think\facade\Cache;
use libs\WXAuth;
use wxGetPhone\WxBizDataCrypt;

class Auth extends BaseController
{
    /**
     * 用户登录
     * @return \think\Response
     */
    public function login()
    {
        $code = $this->request->data['code'];
        // 调用微信接口获取openid和sessionKey
        $wxResult = $this->getWxOpenid($code);
        if (!$wxResult) {
            return result(FAIL, '登录失败');
        }

        // 查找用户是否存在
        $user = Db::table('wxappUser')->where('openId', $wxResult['openid'])->find();
        
        // 用户不存在，创建新用户
        if (!$user) {
            // 生成UUID
            $uuid = createUuid();
            // 插入新用户
            //avatar 用当前的域名地址拼接
            $avatar = request()->domain().'/images/default-avatar.png';
            $userData = [
                'uuid' => $uuid,
                'nickname' => 'UED.'.rand(10000, 99999),
                'avatarUrl' => $avatar,
                'openId' => $wxResult['openid'],
                'unicode' => isset($wxResult['unionid']) ? $wxResult['unionid'] : '',
            ];
            
            Db::table('wxappUser')->insert($userData);
            
            // 重新获取用户
            $user = Db::table('wxappUser')->where('openId', $wxResult['openid'])->find();
        }

        // 生成token
        $token = generateToken($user['uuid']);
        
        // 返回结果
        return result(SUCCESS, '', [
            'sessionKey' => $wxResult['session_key'],
            'wxappUserUuid' => $user['uuid'],
            'token' => $token,
            'hasCellPhone' => !empty($user['cellPhone'])
        ]);
    }

    /**
     * 保存手机号码
     * @return \think\Response
     */
    public function savePhone()
    {
        $data = $this->request->data;
        $encryptedData = $data['encryptedData'];
        $iv = $data['iv'];
        $sessionKey = $data['sessionKey'];
        // 获取当前用户ID
        $uuid = $this->request->uuid;
        
        // 获取小程序配置
        $config = DB::table('config')->where(1)->field(['appid,appSecret'])->find();
        if (!$config) {
            return result(FAIL, '系统配置错误');
        }
        
        $pc = new WXBizDataCrypt(rtrim($config['appid']), $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        // 解密手机号
        if ($errCode != 0) {
            return result(FAIL, '获取手机号失败');
        }
        // 解析手机号数据
        $data = json_decode($data);
        $check = DB::table('wxappUser')
        ->where('cellPhone',$data->phoneNumber)
        ->where('uuid','<>',$uuid)
        ->value('id');
        if($check) return result(FAIL,'','该手机号码已绑定其他账户,请更换手机号码进行绑定'); 

        // 更新用户手机号
        $result = Db::table('wxappUser')->where('uuid', $uuid)->update([
            'cellPhone' => $data->phoneNumber,
        ]);
        
        if ($result) {
            return result(SUCCESS, '保存成功');
        }
        return result(FAIL, '保存失败');
    }

    /**
     * 用户授权信息保存
     * @return \think\Response
     */
    public function authorization()
    {
        $userInfo = $this->request->data['userInfo'];
        $uuid = $this->request->userId;

        $data = [
            'nickname' => $userInfo['nickName'],
            'avatarUrl' => $userInfo['avatarUrl'],
        ];

        $result = Db::table('wxappUser')->where('uuid', $uuid)->update($data);
        if ($result) {
            return result(SUCCESS, '保存成功');
        }
        return result(FAIL, '保存失败');
    }

    /**
     * 会员注册
     * @return \think\Response
     */
    public function register()
    {
        $data = $this->request->data;
        $uuid = $this->request->userId;

        // 验证手机验证码
        if (!$this->checkPhoneCode($data['cellPhone'], $data['code'])) {
            return result(FAIL, '验证码错误');
        }

        $userData = [
            'cellPhone' => $data['cellPhone'],
            'updateTime' => date('Y-m-d H:i:s')
        ];

        $result = Db::table('wxappUser')->where('uuid', $uuid)->update($userData);
        if ($result) {
            return result(SUCCESS, '注册成功');
        }
        return result(FAIL, '注册失败');
    }

    /**
     * 企业认证
     * @return \think\Response
     */
    public function companyAuth()
    {
        $data = $this->request->data;
        $uuid = $this->request->userId;

        // 处理营业执照上传
        $businessLicense = $this->uploadFile($data['businessLicense']);
        if (!$businessLicense) {
            return result(FAIL, '营业执照上传失败');
        }

        $companyData = [
            'companyName' => $data['companyName'],
            'businessLicense' => $businessLicense,
            'legalPerson' => $data['legalPerson'],
            'contactPhone' => $data['contactPhone'],
            'status' => 0,
            'userUuid' => $uuid,
            'createTime' => date('Y-m-d H:i:s'),
            'updateTime' => date('Y-m-d H:i:s')
        ];

        $result = Db::table('company_auth')->insert($companyData);
        if ($result) {
            return result(SUCCESS, '提交成功，等待审核');
        }
        return result(FAIL, '提交失败');
    }

    /**
     * 获取微信openid
     * @param string $code
     * @return array|bool
     */
    protected function getWxOpenid($code)
    {
        // 使用提供的WXAuth类
        $wxAuth = new WXAuth('user');
        $wxResult = $wxAuth->getOpenId($code);
        
        if (!$wxResult || isset($wxResult['errcode'])) {
            return false;
        }
        
        // 获取unionid
        if (!isset($wxResult['unionid']) && isset($wxResult['openid'])) {
            $unionidResult = $wxAuth->getUnionId($wxResult['openid']);
            if ($unionidResult && isset($unionidResult['unionid'])) {
                $wxResult['unionid'] = $unionidResult['unionid'];
            }
        }
        
        return $wxResult;
    }

    /**
     * 验证手机验证码
     * @param string $phone
     * @param string $code
     * @return bool
     */
    protected function checkPhoneCode($phone, $code)
    {
        $cacheCode = Cache::get('phone_code_' . $phone);
        return $cacheCode === $code;
    }

    /**
     * 上传文件
     * @param string $file
     * @return string|bool
     */
    protected function uploadFile($file)
    {
        // 实现文件上传逻辑
        // 这里简单处理，实际应该使用ThinkPHP的上传功能
        if (empty($file)) {
            return false;
        }
        
        // 假设是base64编码的图片
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file, $matches)) {
            $type = $matches[2];
            $fileName = uniqid() . '.' . $type;
            $filePath = '/uploads/business/' . date('Ymd') . '/';
            $realPath = public_path() . $filePath;
            
            // 创建目录
            if (!is_dir($realPath)) {
                mkdir($realPath, 0777, true);
            }
            
            // 保存文件
            $data = base64_decode(str_replace($matches[1], '', $file));
            if (file_put_contents($realPath . $fileName, $data)) {
                return $filePath . $fileName;
            }
        }
        
        return false;
    }
    
 
} 